<template>
  <div class="page-container">
    <div class="common-content-wrap">
      <TrTable
        ref="trTable"
        v-model="searchParams"
        :btnList="btnList"
        :searchShowList="searchShowList"
        :tableData="tableData"
        :tableColumn="tableColumn"
        :total="totalNum"
        requestName="getList"
        @add="operateHandle($event, 'add')"
        @delete="operateHandle($event, 'delete')"
        @rowDelete="operateHandle($event, 'rowDelete')"
        @rowEdit="operateHandle($event, 'rowEdit')"
        @rowEnable="operateHandle($event, 'rowEnable')"
        @rowUnenable="operateHandle($event, 'rowUnenable')"
        @rowResetPwd="operateHandle($event, 'rowResetPwd')"
      />
    </div>
    <TrFormPopup
      v-model="isShowEdit"
      :title="checkTitle"
      :valueObj.sync="formObj"
      :formData="formData"
      :list="checkList"
      @close="isShowEdit = false"
      @confrim="confrimHandle"
    />
  </div>
</template>

<script>
import {
  getList,
  add,
  edit,
  remove,
  updateStatus,
  resetPassWord,
} from "@/api/user/user.js";
import { getList as getRoleList } from "@/api/user/role.js";
import { getColor } from "@/utils/billColor";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrFormPopup from "@/components/Tr-form/Tr-form-popup.vue";
import moment from "moment";
export default {
  name: "UserBox",
  components: {
    TrTable,
    TrFormPopup,
  },
  data: () => ({
    isShowEdit: false,
    formObj: {},
    formData: {},
    btnList: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
      // {
      //   label: "删除",
      //   option: "delete",
      //   color: "white",
      // },
    ],
    totalNum: 0,
    tableData: [],
    searchParams: {
      pageNo: 1,
      pageSize: 10,
    },
    searchShowList: [
      {
        id: "username",
        label: "登录账号",
        type: "input",
        value: "",
        width: 25,
      },

      {
        id: "userRealName",
        label: "用户姓名",
        type: "input",
        value: "",
        width: 25,
      },
      {
        id: "validEndDateStr",
        type: "date",
        width: 25,
        label: "到期时间",
        value: "",
        format: "yyyy-MM-dd",
      },
    ],
    tableColumn: [
      {
        type: "text",
        label: "登录账号",
        value: "username",
      },
      {
        type: "text",
        label: "所属租户",
        value: "userTypeName",
      },
      {
        type: "text",
        label: "用户姓名",
        value: "userRealName",
      },
      {
        type: "text",
        label: "所属角色",
        value: "roleName",
      },
      {
        type: "text",
        label: "用户平台",
        value: "platformTypeName",
      },
      {
        type: "text",
        label: "开始时间",
        value: "validStartDateName",
      },
      {
        type: "text",
        label: "到期时间",
        value: "validEndDateName",
      },
      {
        type: "text",
        label: "状态",
        value: "statusName",
      },
      {
        type: "option",
        label: "操作",
        width: 120,
        fixed: "right",
        showBtnList: [
          {
            label: "编辑",
            option: "rowEdit",
          },

          // {
          //   label: "角色配置",
          //   option: "rowRoleSet",
          // },
        ],
        hideBtnList: [
          {
            label: "重置密码",
            option: "rowResetPwd",
          },
          {
            label: "账号启用",
            option: "rowEnable",
          },
          {
            label: "账号停用",
            option: "rowUnenable",
          },
          {
            label: "删除",
            option: "rowDelete",
          },
        ],
      },
    ],
    currentHandle: "",
    popupList: [
      {
        label: "用户账号",
        type: "input",
        width: 50,
        value: "",
        id: "username",
      },
      {
        label: "用户类型",
        type: "select",
        width: 50,
        list: [
          {
            label: "管理组",
            value: 0,
          },
          {
            label: "普通用户",
            value: 1,
          },
        ],
        value: "",
        id: "userType",
      },
      {
        label: "用户平台",
        type: "select",
        width: 50,
        list: [
          {
            label: "APP",
            value: 0,
          },
          {
            label: "PC",
            value: 1,
          },
        ],
        value: "",
        id: "platformType",
      },
      {
        label: "用户姓名",
        type: "input",
        width: 50,
        value: "",
        id: "userRealName",
      },
      {
        label: "用户昵称",
        type: "input",
        width: 50,
        value: "",
        id: "nickname",
      },
      {
        startStr: "validStartDateStr",
        endStr: "validEndDateStr",
        label: "有效时间范围",
        type: "daterange",
        width: 50,
        value: [],
        id: "date",
      },
      {
        label: "所属角色",
        type: "select",
        width: 50,
        list: [],
        value: [],
        id: "roleIds",
        multiple: true,
      },
      // {
      //   label: "状态",
      //   type: "radio",
      //   width: 50,
      //   value: 0,
      //   id: "status",
      //   list: [
      //     {
      //       label: "正常",
      //       value: 0,
      //     },
      //     {
      //       label: "停用",
      //       value: 1,
      //     },
      //   ],
      // },
      {
        label: "账号密码",
        type: "input",
        width: 50,
        value: "",
        id: "password",
      },
      {
        label: "备注",
        type: "textarea",
        width: 100,
        value: "",
        id: "remark",
        isNeed: false,
      },
    ],
  }),
  computed: {
    checkTitle() {
      return this.currentHandle == "add" ? "新增" : "编辑";
    },
    checkList() {
      let fList = this.popupList.filter((item) => {
        return item.id != "password";
      });
      // let roleList = this.popupList.filter((item) => {
      //   return item.id == "roleIdList";
      // });
      return this.currentHandle == "add" ? this.popupList : fList;
    },
  },
  methods: {
    async operateHandle(val, type) {
      console.log(val, "<<<<<<<<<<<,");
      this.currentHandle = type;
      if (type == "rowEdit") {
        val.date = [val.validStartDateName, val.validEndDateName];
        val.roleIds = val.roleIdList;
      }
      this.formData = type == "rowEdit" ? val : {};

      switch (type) {
        // case "delete":
        //   this.remove(this.ids);
        //   return;
        case "rowResetPwd":
          this.resetPassWordHandle(val.id);
          return;
        case "rowEnable":
        case "rowUnenable":
          this.updateStatusHandle(val);
          return;
        // case "roleSet": {
        //   let res = await grantTree();
        //   let roRes = await getRole(this.ids.join(","));
        //   const meColumn = this.$findByProperty(
        //     this.powerList,
        //     "id",
        //     "menuIds"
        //   );
        //   meColumn.list = res.data.data.menu;
        //   meColumn.value = roRes.data.data.menu;
        //   console.log(meColumn.value, "meColumn.value");
        //   this.isShowRolePopup = true;
        //   return;
        // }
        case "rowDelete":
          this.removeHandle(val.id);
          return;
      }
      this.isShowEdit = true;
    },

    resetPassWordHandle(id) {
      let params = {
        id,
        password: "123456",
      };
      this.$textShow({
        title: this.$t("tip.label"),
        content: ["是否将该账户密码重置为123456？"],
      })
        .then(async () => {
          let res = await resetPassWord(params);
          this.$message.success(this.$t("msg.success"));
          // this.$refs.trTable.clearSelect();
          this.getList();
        })
        .catch(() => {});
    },
    removeHandle(id) {
      this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t("tip.delete")],
      })
        .then(async () => {
          let res = await remove(id);
          this.$message.success(this.$t("msg.success"));
          this.$refs.trTable.clearSelect();
          this.getList();
        })
        .catch(() => {});
    },
    async getList() {
      const { data: res } = await getList(this.searchParams);
      console.log(res, ">>>>>>>>>..");
      this.$validateData(res);
      this.tableData = res.list;
      this.tableData.forEach((item) => {
        item["userTypeName"] = this.getUserTypeName(item.userType);
        item["validStartDateName"] = moment(item.validStartDate).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        item["validEndDateName"] = moment(item.validEndDate).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        item["statusName"] = this.getStatusName(item.status);
        item["platformTypeName"] = this.getPlatformName(item.platformType);
        item["statusNameColor"] = getColor("QT", item.status);
        if (item.userRoleRespVOS != "-") {
          item["roleName"] = item.userRoleRespVOS
            .map((val) => val.name)
            .join(",");
          item["roleIdList"] = item.userRoleRespVOS.map((val) => val.id);
        } else {
          item["roleName"] = "-";
          item["roleIdList"] = [];
        }
        item["isShowrowEnable"] = item.status === 0;
        item["isShowrowUnenable"] = item.status === 1;
      });
      this.totalNum = res.total;
    },
    getUserTypeName(status) {
      return status === 0 ? "管理员" : status === 1 ? "普通用户" : "-";
    },
    getPlatformName(status) {
      return status === 0 ? "APP" : status === 1 ? "PC" : "-";
    },
    getStatusName(status) {
      return status === 0 ? "正常" : status === 1 ? "停用" : "-";
    },
    confrimHandle() {
      if (this.currentHandle == "rowEdit") {
        this.formObj.id = this.formData.id;
        this.editHandle(this.formObj);
        return;
      }
      this.addHandle(this.formObj);
    },
    addHandle(row) {
      let params = {
        ...row,
        // nickname: "222",
        // deptId: "1",
        // postIds: "1",
        // email: "geci@iocoder.cn",
        // mobile: "15601691300",
        // sex: 1,
        // avatar: "",
        // userBirthday: "2024-12-21 00:00:00",
      };
      // params.roleIds = params.roleIds.join(",");
      delete params.date;
      add(params).then((res) => {
        this.isShowEdit = false;
        this.formObj = {};
        this.getList();
        this.$message.success(this.$t("msg.success"));
      });
    },
    editHandle(row) {
      edit(row).then((res) => {
        this.isShowEdit = false;
        this.formObj = {};
        this.getList();
        this.$message.success(this.$t("msg.success"));
      });
    },
    updateStatusHandle(row) {
      let params = {
        id: row.id,
        status: row.status === 0 ? 1 : 0,
      };
      let tip =
        row.status === 0
          ? this.$t("tip.unenableTip")
          : this.$t("tip.enableTip");
      this.$textShow({
        title: this.$t("tip.label"),
        content: [tip],
      })
        .then(async () => {
          let res = await updateStatus(params);
          this.$message.success(this.$t("msg.success"));
          // this.$refs.trTable.clearSelect();
          this.getList();
        })
        .catch(() => {});
      // updateStatus(row).then((res) => {
      //   this.isShowEdit = false;
      //   this.formObj = {};
      //   this.getList();
      //   this.$message.success(this.$t("msg.success"));
      // });
    },
    initData() {
      getRoleList({ pageNo: 1, pageSize: 1000, status: 0 }).then((res) => {
        console.log(res, "res.list");
        const column = this.$findByProperty(this.popupList, "id", "roleIds");
        let list = res.data.list.map((item) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
        column.list = list;
      });
    },
  },
  mounted() {
    this.initData();
  },
};
</script>
